#! /usr/bin/env python
# -*- coding: utf-8 -*-
import webview, error, webexec, char, control
from flask import Flask, abort, redirect, url_for, render_template, request, make_response, Markup

app = Flask(__name__)

@app.route('/list',methods=['GET'])
def list():
	tablename=''
	tablename=request.args.get('tablename', '')
	#判断参数是否传入
	if(tablename==''):
		return redirect(url_for('error'))

	#判断表是否存在
	if(webview.chktable(tablename)):
		infolist=webview.getinfo(tablename)
		if(len(infolist)==0):
			return redirect(url_for('error'))
		return render_template('list.html',infolist=infolist)
	else:
		return redirect(url_for('error'))

@app.route('/')
def index():
	tablelist=webview.gettables()
	return render_template('index.html',tablelist=tablelist)

@app.route('/error')
def error():
	return render_template('404.html'), 404

@app.route('/exec',methods=['GET'])
def execute():
	url=''
	deep=''
	#检查cookies
	try:
		tid=request.cookies['tid']
		#检查id存在吗
		if(webexec.chkid(tid)):
			#id存在，说明正在运行
			return 'runing'
		else:
			resp=make_response()
			resp.delete_cookie('tid')
			return resp
	except:
		url=request.args.get('url', '')
		deep=request.args.get('deep', '')
		#检测传入参数正确吗
		if(url=='' or deep=='0'):
			return ''
		#干活
		tid=char.GetID('%s'%char.GetTime())
		resp=make_response()  
		resp.set_cookie('tid',value=tid)
		if(not control.controlrun(url,tid,deep)):
			return ''
		return resp

if __name__ == '__main__':
	app.run(host='0.0.0.0',debug=True)